package com.project.personalfundmanager.client.common;

import com.extjs.gxt.ui.client.core.El;
import com.extjs.gxt.ui.client.event.ComponentEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.FieldEvent;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.widget.Window;
import com.extjs.gxt.ui.client.widget.form.Field;
import com.extjs.gxt.ui.client.widget.form.NumberField;
import com.extjs.gxt.ui.client.widget.form.TextArea;
import com.extjs.gxt.ui.client.widget.form.Validator;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.project.personalfundmanager.client.GreetingService;
import com.project.personalfundmanager.client.GreetingServiceAsync;
import com.project.personalfundmanager.client.facebook.Callback;
import com.project.personalfundmanager.client.taxitems.ParentItem;

@SuppressWarnings( "unchecked" )
public class InputField extends NumberField
{
	private ParentItem tabItem;
	private static Window window = new Window();
	TextArea textArea = new TextArea();

	public InputField( ParentItem tabItem )
	{
		this.tabItem = tabItem;
	}

	@Override
	protected void onRender( Element target, int index )
	{
		super.onRender( target, index );
		trigger = new El( DOM.createImg() );
		trigger.dom.setClassName( "x-input-button" );
		el().appendChild( trigger.dom );
	}

	@Override
	protected void onTriggerClick( ComponentEvent ce )
	{
		GreetingServiceAsync async = ( GreetingServiceAsync ) GWT.create( GreetingService.class );
		async.getInfo( getName(), new Callback<String>()
		{
			public void onSuccess( final String result )
			{
				textArea.setValue( result );
				window.removeAll();
				window.add( textArea );
				window.show();
			};
		} );
		
		textArea.setReadOnly( true );
		textArea.setSize( 400, 200 );
		window.setLayout( new FitLayout() );
		window.setHeading( getFieldLabel() );
	}

	public InputField getInputField( String label, String name, boolean isEditable, final int limit )
	{
		setFieldLabel( label );
		setToolTip( label );
		setName( name );
		setAllowDecimals( false );
		setMessageTarget( "title" );
		setEditable( isEditable );
		setFormat( NumberFormat.getDecimalFormat() );
		addListener( Events.OnChange, new Listener<FieldEvent>()
		{
			public void handleEvent( FieldEvent be )
			{
				tabItem.calculateTotal();
			}
		} );

		if ( limit > 0 )
		{
			setValidator( new Validator()
			{
				public String validate( Field< ? > field, String value )
				{
					if ( field.getValue() != null && ( ( Number ) field.getValue() ).intValue() > limit )
						return "Maximum value for this field is " + limit;

					return null;
				}
			} );
		}

		return this;
	}
}
